package com.biomatch.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.biomatch.domain.ContainerLock;
import com.biomatch.domain.Position;
import com.biomatch.dto.Pagination;
import com.biomatch.mapper.ContainerLockMapper;
import com.biomatch.mapper.PositionMapper;
import com.biomatch.service.PositionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class PositionServiceImpl implements PositionService {


    @Autowired
    private PositionMapper positionMapper;

    @Override
    public IPage<Position> get4Page(Pagination pagination) {
        Page<Position> page = new Page<>(pagination.getCurrent(), pagination.getPageSize());
        return positionMapper.selectPage(page, null);
    }

    @Override
    public List<Position> getAll() {
        return positionMapper.selectList(null);
    }

    @Override
    public Position saveOrUpdate(Position position) {
        if (position.getId() <= 0) {
            QueryWrapper<Position> positionQueryWrapper = new QueryWrapper<>();
            positionQueryWrapper.eq("name", position.getName());
            if (positionMapper.selectCount(positionQueryWrapper) > 0) {
                return null;
            }
            else {
                String code = String.valueOf(new Date().getTime());
                position.setStatus(true);
                position.setPositionId("P" + code.substring(5, code.length()));
                position.setCreateTime(new Date());
                positionMapper.insert(position);
                return position;
            }
        } else {
            QueryWrapper<Position> positionQueryWrapper = new QueryWrapper<>();
            positionQueryWrapper.eq("name", position.getName()).ne("positionid", position.getPositionId());
            if (positionMapper.selectCount(positionQueryWrapper) > 0) {
                return null;
            }
            else {
                position.setUpdateTime(new Date());
                positionMapper.updateById(position);
                return position;
            }
        }
    }

    @Override
    public Position delete(Position position) {
        QueryWrapper<Position> PositionQueryWrapper = new QueryWrapper<>();
        PositionQueryWrapper.eq("positionId", position.getPositionId());
        if (positionMapper.selectCount(PositionQueryWrapper) > 0) {
            positionMapper.deleteById(position.getId());
            return position;
        } else
            {
                return null;
        }
    }
}
